package LeetCode._02算法基础.day11递归回溯;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 挚爱之夕
 * @date 2022 - 03 - 22 - 14:34
 * @Description LeetCode._02算法基础.day11递归回溯
 * @Version 中等
 */
public class _22括号生成 {
    static int n = 3;
    @Test
    public void test(){
        List<String> res = generateParenthesis(n);
        System.out.println(res);
    }
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        backtrack(ans, 0, 0, n);
        return ans;
    }

    StringBuilder cur = new StringBuilder();
    public void backtrack(List<String> ans, int left, int right, int max) {
        if (cur.length() == max * 2) {
            ans.add(cur.toString());
            return;
        }
        /*
        如果左括号数量不大于 n，我们可以放一个左括号。如果右括号数量小于左括号的数量，我们可以放一个右括号。
         */
        if (left < max) {
            cur.append('(');
            backtrack(ans, left + 1, right, max);
            cur.deleteCharAt(cur.length() - 1);
        }
        if (right < left) {
            cur.append(')');
            backtrack(ans, left, right + 1, max);
            cur.deleteCharAt(cur.length() - 1);
        }
    }

}
